package juc.thread.secuity;

import java.util.*;

/*
* 买票案例
* */
public class Test3 {
    private  static Random random=new Random();
    public static void main(String[] args) {
        TailSeller seller = new TailSeller(1000);
        List<Integer>totalSell=new Vector<>();//多线程共享 使用 Vector 不会出现线程安全问题
        List<Thread>threads=new ArrayList<>();
        UUID uuid = UUID.randomUUID();//用交易号来作为锁定标识
        for (int i = 0; i < 900; i++) {
            Thread thread = new Thread(() -> {
                int sell = seller.sell(getRandomNum());
                totalSell.add(sell);
            });
            threads.add(thread);
            thread.start();
        }
        for (Thread thread : threads) {//等待所有线程执行完再统计
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int sum=0;
        for (Integer sell : totalSell) {
            sum+=sell;
        }
        System.out.println("卖票："+sum);
        System.out.println("余票："+seller.getCount());
//        main(args);
    }
    public static int getRandomNum(){
        return random.nextInt(5)+1;
    }
    static class TailSeller{
        private int count;

        public TailSeller(int count) {
            this.count = count;
        }

        public int getCount() {
            return count;
        }
        public synchronized int sell(int num){
              if(num<=count){
                  System.out.println("num:"+num);
                  count-=num;
                  return num;
              }
              return 0;
        }
    }
}
